package autotrade.data.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;

public abstract class AbstractAspDataHandler {
	public void doGetDataFromAsp(HashMap<String, String> param) {
		if(!isValidParam(param)) return;
		String url = getURL();
		int i = 0;
		for(String key : param.keySet()) {
			if(i == 0) url += "?";
			else url += "&";
			url += (key+"="+param.get(key));
			i++;
		}
		
		URLConnection conn = null;
		BufferedReader input = null;
		try {
			conn = new URL(url).openConnection();
			input = new BufferedReader(new InputStreamReader(conn.getInputStream(), getCharset()));
			String str = null;
			ArrayList<String> lines = new ArrayList<String>();
			while((str = input.readLine()) != null) {
				lines.add(str);
			}
			readData(lines);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(input != null) input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected abstract void readData(ArrayList<String> lines);
	protected abstract String getURL();
	protected abstract String getCharset();
	protected abstract boolean isValidParam(HashMap<String, String> param);
}
